﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using AMail.Common;
using AMail.Common.Events;
using AMail.Common.Interfaces.Data;
using AMail.Common.Interfaces.Services;
using Elentok.Common;
using Elentok.Common.Wpf;
using Elentok.Common.Wpf.Dialogs;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Modularity;
using Microsoft.Practices.Composite.Presentation.Commands;
using Microsoft.Practices.Unity;
using Microsoft.Win32;
using System;
using AMail.Modules.Archive.Services;

namespace AMail.Modules.Archive
{
  public class ArchiveModule : IModule
  {
    private List<DelegateCommand<object>> commands;

    public ArchiveModule(IEventAggregator eventAggregator,
      IUnityContainer container)
    {
      container.RegisterType<IArchiveService, ArchiveService>(new ContainerControlledLifetimeManager());

      eventAggregator.GetEvent<ActiveArchiveChangedEvent>().Subscribe(OnActiveArchiveChanged, true);

      var builder = container.Resolve<ArchiveCommandsBuilder>();
      commands = builder.CreateAndRegisterCommands();
    }

    #region IModule Members

    public void Initialize()
    {
    }

    #endregion

    #region Event Handlers

    private void OnActiveArchiveChanged(ActiveArchiveChangedEventArgs eventArgs)
    {
      if (eventArgs.OldArchive != null)
        eventArgs.OldArchive.PropertyChanged -= new PropertyChangedEventHandler(Archive_PropertyChanged);

      if (eventArgs.NewArchive != null)
        eventArgs.NewArchive.PropertyChanged += new PropertyChangedEventHandler(Archive_PropertyChanged);

      UpdateCommands();
    }

    private void Archive_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
      UpdateCommands();
    }

    private void UpdateCommands()
    {
      foreach (var command in this.commands)
        command.RaiseCanExecuteChanged();
    }

    #endregion
  }
}
